package com.example.demo.config;

import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

/**
 * 数据库连接配置类
 */
public class DataSourceConfig {
    private static final HikariDataSource dataSource;

    static {
        try {
            Properties props = new Properties();
            InputStream input = DataSourceConfig.class.getClassLoader().getResourceAsStream("database.properties");
            if (input == null) {
                throw new RuntimeException("找不到数据库配置文件");
            }
            props.load(input);

            HikariConfig config = new HikariConfig();
            config.setJdbcUrl(props.getProperty("jdbc.url"));
            config.setUsername(props.getProperty("jdbc.username"));
            config.setPassword(props.getProperty("jdbc.password"));
            config.setDriverClassName(props.getProperty("jdbc.driver"));
            
            // 连接池配置
            config.setMaximumPoolSize(10);
            config.setMinimumIdle(5);
            config.setConnectionTimeout(30000);
            config.setIdleTimeout(600000);
            config.setMaxLifetime(1800000);
            
            dataSource = new HikariDataSource(config);
            
        } catch (Exception e) {
            throw new RuntimeException("数据库连接池初始化失败: " + e.getMessage(), e);
        }
    }

    // 获取数据库连接
    public static Connection getConnection() throws SQLException {
        return dataSource.getConnection();
    }

    // 获取数据源对象
    public static HikariDataSource getDataSource() {
        return dataSource;
    }
}